package com.octopus.samples.gitee;

import com.octopus.core.Request;
import com.octopus.core.Response;
import com.octopus.core.parser.HtmlParser;
import com.octopus.core.parser.ParseException;
import com.octopus.core.parser.ParseResult;
import com.octopus.core.result.Result;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

/**
 * 项目列表页面解析
 *
 * @author shoulai.yang@gmail.com
 * @date 2019/08/02
 */
public class ProjectsParser extends HtmlParser {

  @Override
  public ParseResult parse(Document document, Response response) throws ParseException {
    ParseResult result = new ParseResult();
    Collection<Project> projects = new ArrayList<>();
    // 解析项目列表
    document
        .select(".explore-repo__list > .item")
        .forEach(
            element -> {
              Project project = new Project();
              String author = element.select("a.avatar > img").first().attr("alt");
              project.setAuthor(author);
              String name = element.select("a.project-namespace-path").first().attr("title");
              project.setName(name.substring(name.indexOf("/") + 1));
              List<String> metas = new ArrayList<>();
              element
                  .select("span.project-meta > a")
                  .forEach(
                      e -> {
                        metas.add(e.text());
                      });
              project.setMetas(metas);
              element
                  .select("div.explore-project__meta-social > a")
                  .forEach(
                      e -> {
                        String title = e.attr("title");
                        String count = e.select(">span").first().text();
                        switch (title) {
                          case "关注数":
                            project.setWatchCount(count);
                            break;
                          case "收藏数":
                            project.setCollectCount(count);
                            break;
                          case "Fork 数":
                            project.setForkCount(count);
                            break;
                          default:
                            break;
                        }
                      });
              project.setDesc(element.select("div.project-desc").first().text());
              project.setLatest(element.select("div.project-latest > span").first().attr("title"));
              Element icon = element.select("i.icon-recommended").first();
              project.setRecommend(icon != null);
              projects.add(project);
            });
    result.body(Result.me().obj(projects));
    // 获取下一页
    Element lastPage = document.select("div.pagination > a > i[class='fa fa-angle-right']").first();
    if (lastPage != null) {
      result.requests(Request.me("https://gitee.com" + lastPage.parent().attr("href")));
    }
    return result;
  }
}
